package com.auth.config.security;

import com.auth.config.response.CustomWebResponseExceptionTranslator;
import com.auth.config.token.AuthOAuth2TokenEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;

import javax.sql.DataSource;

/**
 * 当前类为Oauth2 server的配置类(需要继承特定的父类 AuthorizationServerConfigurerAdapter)
 * @author HeWei123 \
 */
@Configuration
/**
 * // 开启认证服务器功能
 */
@EnableAuthorizationServer
public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;


    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private DefaultTokenServices defaultTokenServices;

    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;


    @Autowired
    private DataSource dataSource;


    /**
     * 认证服务器最终是以api接口的方式对外提供服务(校验合法性并生成令牌、校验令牌等)
     * 那么，以api接口方式对外的话，就涉及到接口的访问权限，我们需要在这里进行必要的配置
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 相当于打开endpoints 访问接口的开关，这样的话后期我们能够访问该接口
        security
                // 允许客户端表单认证
                .allowFormAuthenticationForClients()
                //认证token
                .tokenKeyAccess("permitAll()")
                // 开启端口/oauth/token_key的访问权限（允许）
                .tokenKeyAccess("permitAll()")
                // 开启端口/oauth/check_token的访问权限（允许）
                .checkTokenAccess("permitAll()");

//                .passwordEncoder(passwordEncoder());
    }



    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }



    /**
     * 从数据库中读取客户端配置
     * @return
     */
    @Bean
    public ClientDetailsService createClientDetailsService() {
        JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(dataSource);
        jdbcClientDetailsService.setPasswordEncoder(bCryptPasswordEncoder());
        return jdbcClientDetailsService;
    }

    /**
     * 客户端详情配置
     *  参数配置详情
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(createClientDetailsService());
    }



    /**
     * 认证服务器token的配置，令牌生成策略，增强实现，
     * 都是在这里配置
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
      this.authorizationServerEndpointsConfigurer(endpoints);
    }

    /**
     * 生成 AuthOAuth2TokenEndpoint 对象 并且加载所以自定义配置项
     *  （AuthOAuth2TokenEndpoint对象生成顺序会比configure(AuthorizationServerEndpointsConfigurer endpoints)方法靠前
     *      所以如果不提前加载配置项，会让自定义token接口所以基于AuthorizationServerEndpointsConfigurer的配置全部变成默认（基于内存））
     * @return AuthOAuth2TokenEndpoint
     */
    @Bean
    public AuthOAuth2TokenEndpoint authOAuth2TokenEndpoint(){
        AuthOAuth2TokenEndpoint authOAuth2TokenEndpoint = new AuthOAuth2TokenEndpoint();
        AuthorizationServerEndpointsConfigurer endpoints = new AuthorizationServerEndpointsConfigurer();
        this.authorizationServerEndpointsConfigurer(endpoints);
        authOAuth2TokenEndpoint.setClientDetailsService(createClientDetailsService());
        authOAuth2TokenEndpoint.setProviderExceptionHandler(endpoints.getExceptionTranslator());
        authOAuth2TokenEndpoint.setTokenGranter(endpoints.getTokenGranter());
        authOAuth2TokenEndpoint.setOAuth2RequestFactory();
        authOAuth2TokenEndpoint.setoAuth2RequestValidator(endpoints.getOAuth2RequestValidator());
        return authOAuth2TokenEndpoint;
    }

    public void authorizationServerEndpointsConfigurer(AuthorizationServerEndpointsConfigurer endpoints){
        endpoints
                //加载用户信息 接口实现
                .userDetailsService(userDetailsService)
                .exceptionTranslator(new CustomWebResponseExceptionTranslator())
                // 令牌服务实现
                .tokenServices(defaultTokenServices)
                // 指定认证管理器，随后注入一个到当前类使用即可
                .authenticationManager(authenticationManager)
                .authorizationCodeServices(authorizationCodeServices)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .setClientDetailsService(createClientDetailsService());

    }


}
